
  <template>
  <div class="container">
    <el-button type="success" round size="small" @click="centerDialogVisible = true">用户菜单权限</el-button>
    <Teleport to="#app">
      <el-dialog @close="close" v-model="centerDialogVisible" title="用户菜单权限" width="30%">
        <el-tree ref="treeRef" node-key="id" :default-expanded-keys="defaultCheckedKeys" :default-checked-keys="defaultCheckedKeys" :data="treeData" :props="treeProps" show-checkbox />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="close">关闭</el-button>
            <el-button type="primary" @click="submitForm() ">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </Teleport>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue'
import { getMenuList, userMenu, queryUserMenuNumber } from '@/api/menu.js'
let centerDialogVisible = ref(false)
const treeProps = {
  label: 'name',
  children: 'children'
}
const props = defineProps({
  id: {
    type: Number
  }
})
const defaultCheckedKeys = ref([])
let treeData = ref([])
const close = () => {
  centerDialogVisible.value = false
  treeRef.value.setCheckedKeys(defaultCheckedKeys.value, false)
}
onMounted(() => {
  getMenuListFn()
  queryUserMenuNumberFn(props.id)
})
const getMenuListFn = () => {
  getMenuList().then(res => {
    treeData.value = res.data
  })
}
const treeRef = ref()
const submitForm = () => {
  const data = {
    id: props.id,
    menuList: treeRef.value.getCheckedKeys(false)
  }
  userMenuFn(data)
}
const { proxy } = getCurrentInstance()
const userMenuFn = data => {
  userMenu(data).then(res => {
    if (res.data) {
      defaultCheckedKeys.value = treeRef.value.getCheckedKeys(false)
      proxy.$Message({
        type: 'success',
        message: res.msg
      })
      centerDialogVisible.value = false
    } else {
      proxy.$Message.error(res.msg)
      centerDialogVisible.value = false
    }
  })
}

const queryUserMenuNumberFn = id => {
  queryUserMenuNumber(id).then(res => {
    defaultCheckedKeys.value = res.data
  })
}
</script>
<style scoped>
</style>